# Copyright (C) 2007 "dbsolution sas" 
#
# This file is part of Weebotee.
#
# Weebotee is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Weebotee is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Weebotee.  If not, see <http://www.gnu.org/licenses/>.

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.contrib.auth.models import User
from django import newforms as forms
from apps.core.models.Udetail import Udetail
import datetime

from django.contrib.auth.decorators import *
from apps.core.backend.views.forms.user_form import *
from libs.utils import mails
from apps.core.models.section import Section

@permission_required("is_staff")
def users(request):
    us = User.objects.all()
    return render_to_response('admin_users.html',  locals())


def registerUserProxy(request):
    ''' Fake Proxy
        
        Questa vista simula un proxy,
        in modo da far funzionare il form di registrazione con ajax anche in 
        locale.
    '''
    form = BaseRegistrationForm(request.POST)
    if form.is_valid():
        form.save()
        msg = '<div id="form-accepted"><h1 style="color:#000";>Registrazione Completata!</h1>a breve riceverai un\' email con i codici di accesso.</div>'
    else:
        msg  = '<div id="form-errors">Attenzione! I seguenti campi non sono stati compilati correttamente'
        msg += ''.join(['<div><strong>%s</strong></div>%s' % (k,v) for k,v in form.errors.items()])
        msg += '</div>'
    return HttpResponse(msg)


def registerUser(request):
    if request.POST:
        form = BaseRegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            msg = '<div id="form-accepted"><h1 style="color:#000";>Registrazione Completata!</h1>a breve riceverai un\' email con i codici di accesso.</div>'
        else:
            msg  = '<div id="form-errors">Attenzione! I seguenti campi non sono stati compilati correttamente'
            msg += ''.join(['<div><strong>%s</strong></div>%s' % (k,v) for k,v in form.errors.items()])
            msg += '</div>'
        return HttpResponse(msg)
    return HttpResponseRedirect("/")
    

@permission_required("is_staff")
def addUser(request):

    if request.POST:
        form = userCreationForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/admin/users/"+form.cleaned_data['username'])
    else:
        form = userCreationForm()
    return render_to_response("admin_user_add.html",  locals())

@permission_required("is_staff")
def editUser(request, name):
    us = User.objects.filter(username=name)
    if us:
        us = us[0]
    else:
        return HttpResponseRedirect("/admin/users") 
    ud = Udetail.Udetail.objects.filter(user=us.id)
    if ud:
        ud = ud[0]
    else:
        ud = Udetail.Udetail()
    initial = {"username":us.username, "is_active":us.is_active, "is_staff":us.is_staff, "is_superuser":us.is_superuser, "email":us.email,  "utype":ud.user_type, "first_name":us.first_name, "last_name":us.last_name, "web_site":ud.website, "address":ud.address, "city":ud.city, "prov":ud.prov, "cap":ud.cap, "company":ud.company, "tel":ud.tel, "fax":ud.fax,"piva":ud.piva}
    if request.POST:
        form = userForm(us.username, data=request.POST, initial=initial)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/admin/users")
    else:
        form = userForm(us.username, initial=initial)
    return render_to_response("admin_user_edit.html", locals())
 
@permission_required("is_staff")
def deleteUser(request,  name):
    u = User.objects.filter(username=name)
    if u: u[0].delete()
    return HttpResponseRedirect("/admin/users")

@permission_required("is_staff")
def profileDetails(request, name):
    try:
        u = User.objects.get(username__exact=name)
        title = "Dettaglio Utente"
        details = u.__dict__
    except:
        pass
    return render_to_response('details_list.html', locals())
